﻿using UnityEngine;
using System.Collections;
using System;
using NCmd;
using UnityEngine.SceneManagement;

/// <summary>
/// 地图加载器
/// </summary>
public class MapLoader : Singleton<MapLoader>
{
    AsyncOperation _curAO;

    public Action LoadDoneCallback;
    public void LoadMap(string path, Action loadEndCallback)
    {
        loadBegin();
        Debug.Log("正在加载地图：" + path);
        // 检查地图合法性
        _curAO = SceneManager.LoadSceneAsync(path);

        LoadDoneCallback = loadEndCallback;
        QuickCoroutine.instance.Go.StartCoroutine(WatchLoadProgress());
    }

    IEnumerator WatchLoadProgress()
    {
        yield return new WaitForSeconds(0.02f);
        while (true)
        {
            if (_curAO.isDone)
            {
                if (LoadDoneCallback != null)
                {
                    LoadDoneCallback.Invoke();
                }
                LoadDoneCallback = null;
                loadEnd();
                yield break;
            }

            yield return new WaitForSeconds(0.02f);
        }
    }

    private void loadBegin()
    {
        // 加载地图时，消息进入阻塞模式
        Net.instance.PauseState = true;
        UIManager.instance.EnableEventSystem = false;
        LoadingMgr.instance.Begin();
    }
    private void loadEnd()
    {
        // 地图加载完毕，场景准备完毕，消息放开
        Net.instance.PauseState = false;
        UIManager.instance.EnableEventSystem = true;
        LoadingMgr.instance.End();
    }

    /// <summary>
    /// 重置场景
    /// </summary>
    private void Reset()
    {
    }

    #region 接收消息
    #endregion 接收消息
}
